/**
 * 使用react-intl-universal进行语言切换
 * 会刷新页面
 */
import React, { useState, useEffect } from 'react'
import intl from 'react-intl-universal';
import US from './en-US'
import CN from './zh-CN'
import { getState, setState } from '@/common/state'
import { Select } from 'antd'
const { Option } = Select;
const key = 'language'
const locales = {
    "en-US": US,
    "zh-CN": CN,
    "en_d": require('./en_d.json')
};
export const SUPPOER_LOCALES = [
    {
        name: 'English',
        value: 'en-US'
    },
    {
        name: '简体中文',
        value: 'zh-CN'
    },
    {
        name: '默认',
        value: 'en_d'
    }
];


/**
 * 语言切换组件
 * @returns 
 */
export function LanguageSelect({ width = 120 } = {}) {
    const options = SUPPOER_LOCALES.map(({ name, value }) => <Option key={value} value={value}>{name}</Option>)
    const handleChange = value => {
        setState(key, value)
        setTimeout(() => {
            window.location.search = `?lang=${value}` // 会刷新浏览器
        }, 400)
    };
    return (<Select defaultValue={getState(key)} style={{ width }} onChange={handleChange}>
        {options}
    </Select>)
}


/**
 * 使用hooks实现语言切换
 */
export function useLanguage() {
    const [, setLoca] = useState(false)
    useEffect(() => {
        let currentLocale = intl.determineLocale({
            urlLocaleKey: 'lang',
            cookieLocaleKey: 'lang' // 根据url的尾部标识来时别现在的语言环境
        }) || "zh-CN"
        intl.init({ currentLocale, locales }).then(() => {
            setLoca(true)
        })
    }, [])
}
